package com.example.authority.controller;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.common.Result;
import com.example.authority.entity.jueseTop5;
import com.example.authority.service.UserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


import com.example.authority.service.GenshinjuseService;
import com.example.authority.entity.Genshinjuse ;
import com.example.authority.service.UserhaveService;
import com.example.authority.entity.Userhave;



/**
 * @program: authority-v3.0.7
 * @ClassName:UserhaveController
 * @description: UserhaveController前端控制器
 * @author:dyy
 * @Version 3.0
 **/
@Tag(name = "拥有角色 前端控制器")
    @RestController
@RequestMapping("/userhave")
    public class UserhaveController {

@Resource
private UserhaveService userhaveService;
@Resource
private GenshinjuseService genshinjuseService;
@Resource
private UserRoleService userRoleService;

/**
 * 新增
 * @param userhave
 * @return
 */
@Operation(summary = "新增")
@PostMapping
public Result save(@RequestBody Userhave userhave){
        Object loginId = StpUtil.getLoginId();
        if (loginId instanceof String) {
                userhave.setUserId(Long.valueOf((String) loginId));
        } else if (loginId instanceof Long) {
                userhave.setUserId((Long) loginId);
        }
        LambdaQueryWrapper<Userhave> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Userhave::getName, userhave.getName());
        queryWrapper.eq(Userhave::getUserId, loginId);
        boolean exists = userhaveService.count(queryWrapper) > 0;

        if (exists) {
                return Result.error("角色已存在，无法保存。");
        }
        return Result.success(userhaveService.save(userhave));
        }
/**
* 修改
*
* @param userhave
* @return
*/
@Operation(summary = "修改")
@PutMapping("/{id}")
public Result update(@PathVariable Long id,@RequestBody Userhave userhave) {
        return Result.success(userhaveService.updateById(userhave));
        }

/**
 * 查询所有Userhave
 * @return
 */
@Operation(summary = "查询所有Userhave")
@GetMapping
public Result findAll(){
        return Result.success(userhaveService.list());
        }

/**
 * 查询前五名的角色拥有量
 */
@Operation(summary = "查询前五名的角色拥有量")
@GetMapping("/five")
public Result findAllWithFive(){
        QueryWrapper<Userhave> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("name, COUNT(*) as count")
                .groupBy("name")
                .orderByDesc("count")
                .last("LIMIT 5");
        List<Map<String, Object>> topFiveList = userhaveService.listMaps(queryWrapper);
        List<jueseTop5> resultList = new ArrayList<>();
        for (Map<String, Object> map : topFiveList) {
                jueseTop5 dto = new jueseTop5();
                dto.setName((Long) map.get("name"));
                dto.setCount((Long) map.get("count"));
                resultList.add(dto);
        }
        for(jueseTop5 dto : resultList){
                Genshinjuse juese= genshinjuseService.getById(dto.getName());
                if(juese!=null){
                        dto.setNames(juese.getName());
                }
        }
        return Result.success(resultList);
}

        /**
  * 获取单个
  * @param id
  * @return
  */
@Operation(summary = "获取单个")
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id){
        return Result.success(userhaveService.getById(id));
        }
/**
 * 分页显示
 * @param
 * @param pageNum
 * @param pageSize
 * @return
 */
@Operation(summary = "分页显示")
@GetMapping("/page")
public Result findPage(
        @RequestParam(defaultValue = "") Long name,
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize){

        LambdaQueryWrapper<Userhave>queryWrapper=new LambdaQueryWrapper();
        if (name!=null&&name!=0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Userhave::getName,name);
        }

        // 获取当前用户ID
        Long currentUserId = Long.valueOf(StpUtil.getLoginId().toString());
        List<Long> roleIds = userRoleService.getRoleIds(currentUserId, "PC");

        if(roleIds.get(0) !=1){
                // 添加当前用户ID的查询条件
                queryWrapper.eq(Userhave::getUserId, currentUserId); // 假设Userhave类中有userId字段
        }

        queryWrapper.orderByDesc(Userhave::getId);
        Page<Userhave>page=userhaveService.page(new Page<>(pageNum,pageSize),queryWrapper);
        List<Userhave > records = page.getRecords();
         for (Userhave userhave : records) {
                 Genshinjuse genshinjuse = genshinjuseService.getById(userhave.getName());
                 if (ObjectUtil.isNotEmpty(genshinjuse)){
                     userhave.setGenshinjuse(genshinjuse);
                 }
         }
         page.setRecords(records);


        // 使用 JSONObject 封装结果
        JSONObject result = new JSONObject();
        result.put("roleId", roleIds.isEmpty() ? null : roleIds.get(0));
        result.put("page", page);
         return Result.success(result);

        }
/**
* 单个删除
* @param id
* @return
*/
@Operation(summary = "单个删除")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
        return Result.success(userhaveService.removeById(id));
        }
/**
* 批量删除
* @param ids
* @return
*/
@Operation(summary = "批量删除")
@DeleteMapping("/batch/{ids}")
@Transactional
public Result deleteByIds(@PathVariable String[]ids){
        return Result.success(userhaveService.removeByIds(Arrays.asList(ids)));
        }

/**
 * 批量导出
 * 使用的技术为alibaba下面的easyexcel
 * 写数据
 *
 * @param ids
 * @return
 */
@Operation(summary = "批量导出")
@GetMapping("/batch/export/{ids}")
public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {

        List<Userhave> list = userhaveService.listByIds(Arrays.asList(ids));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("userhave导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Userhave.class).sheet("sheel1").doWrite(list);

        }

/**
 * 批量导入
 * 使用的技术为alibaba下面的easyexcel
 * 读数据
 *
 * @param
 */
@Operation(summary = "批量导入")
@PostMapping("/batch/upload")
public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Userhave.class, new PageReadListener<Userhave>(dataList -> {
        dataList.forEach(entity -> userhaveService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
        }

        }